package cn.kgc.itrip.auth.service.impl;

import cn.kgc.itrip.auth.service.TokenService;
import cn.kgc.itrip.beans.common.Const;
import cn.kgc.itrip.beans.common.ServerResponse;
import cn.kgc.itrip.beans.model.pojo.ItripUser;
import cn.kgc.itrip.beans.model.vo.tokenVo;
import cn.kgc.itrip.util.MD5Util;
import cn.kgc.itrip.util.RedisApi;
import cn.kgc.itrip.util.UserAgentUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 阿泽
 * token 的业务逻辑
 */
@Service("tokenService")
@Slf4j
public class TokenServiceimpl implements TokenService {
    @Resource
    private RedisApi redisApi;
    //生成token(格式为token:设备- 加密的用户名-时间-六位随机数)

    @Override
    public String generateToken(String userAgent, ItripUser user) {
        StringBuffer sb = new StringBuffer();
        sb.append("token:");
        if (UserAgentUtil.CheckAgent(userAgent)) {
            sb.append("mobile-");
        } else {
            sb.append("pc-");
        }
        sb.append(StringUtils.substring(MD5Util.MD5EncodeUtf8(user.getUserCode()), 0, 32));
        SimpleDateFormat time = new SimpleDateFormat("yyyyMMddHHmmss");
        sb.append("-" + time.format(new Date()));
        sb.append("-" + StringUtils.substring(MD5Util.MD5EncodeUtf8(userAgent), 0, 6));
        System.out.println(sb.toString());
        return sb.toString();
    }
    //保存token
    @Override
    public void saveToken(String key, String value, Integer time) {
        //交给redis保存数据
        redisApi.setEx(key, value, time);
    }

    @Override
    public ServerResponse delToken(String token) {
        System.out.println("token" + token);
        //删除成功
        redisApi.del(token);
        return ServerResponse.createBySuccessMessage("退出成功");
    }

    @Override
    public ServerResponse<tokenVo> ReplaceToken(String userAgent, String token) {
        log.info("token置换服务开始");
        if (StringUtils.isBlank(userAgent) || StringUtils.isBlank(token)) {
            log.error("在token置换时候参数丢失");
            return ServerResponse.createByErrorMessage("参数丢失");
        }
        long ttl = redisApi.ttl(token); //获取token的剩余时间
        if (ttl < -1) {
            log.error("当前token的剩余时间是" + ttl + "为无效token");
            return ServerResponse.createByErrorMessage("token失效");
        }
        //判断token是否在保护期
        if (ttl > Const.RedisConst.REPLACEMENT_PROTECTION_TIMEOUT) {
            log.error("当前token处于置换保护期内");
            return ServerResponse.createByErrorMessage("token无法置换");
        }
        //旧token重新设置过期时间
        redisApi.setEx(token, redisApi.get(token), Const.RedisConst.REPLACEMENT_DELAY);
        //设置新token
        String newToken = generateToken(userAgent, JSON.parseObject(redisApi.get(token), ItripUser.class));

        tokenVo tokenVo = new tokenVo();
        tokenVo.setToken(token);
        tokenVo.setExpTime(Const.RedisConst.SESSION_TIMEOUT * 1000L);
        tokenVo.setGenTime(System.currentTimeMillis());
        redisApi.setEx(newToken, redisApi.get(token), Const.RedisConst.SESSION_TIMEOUT);
        return ServerResponse.createBySuccess(tokenVo);
    }
}
